<template>
	<div>
		<el-form-item
			label="题干"
			prop="questionTitle"
			:rules="{
				required: true,
				message: '请输入题干',
				trigger: ['blur', 'change']
			}"
		>
			<template>
				<el-input v-model.trim="questionForm.questionTitle" maxlength="2000">
					<i
						slot="suffix"
						@click="handleEdit(questionForm.questionTitle,'questionTitle')"
						class="el-icon-edit-outline icons"
					/>
				</el-input>
				<span class="tips m-t15">Tips：填空题需要在题干的每个填空处放上（）</span>
			</template>
		</el-form-item>
		<el-form-item
			label="答案"
			required
		>
			<div class="options-group">
				<el-form-item
					v-for="(item, index) in questionForm.optionList"
					:key="item.key+item.optionSeq"
					:prop="'optionList.' + index"
					:rules="{
						required: true, validator:validateOption, trigger: ['blur', 'change']
					}"
				>
					<select-options
						:value="item"
						:index="index"
						:is-show-seq="false"
						:is-add="index===0"
						:is-del="index!=0"
						:is-editor="false"
						:max-length="100"
						@add="add"
						@del="del"
						@edit="handleEdit"
					/>
				</el-form-item>
			</div>
			<span class="tips">Tips：答案的数量要与题干中（）的数量对应</span>
		</el-form-item>
	</div>
</template>
<script >
	import SelectOptions from "../../async/select-options.vue";
	export default {
		name: "q-blank-edit",
		props: {
			value: {
				type: Object,
				default: () => {}
			}
		},
		components: {
			SelectOptions
		},
		data() {
			return {
				questionForm: {}
			};
		},
		watch: {
			value: {
				immediate: true,
				deep: true,
				handler(val) {
					this.questionForm = JSON.parse(JSON.stringify(val));
					if (!val.optionList || !val.optionList.length) {
						this.$set(this.questionForm, "optionList", [
							{
                                optionSeq:'A',
								answerOption: "",
								isAnswer: "Y",
                                answerSeq:1,
                                key: Date.now()
							}
						]);
					} else {
                        this.questionForm.optionList.forEach((option)=>{
                            option.key = Date.now()+Math.random();
                        });
                    }
				}
			},
            'questionForm.optionList':{
                immediate:true,
                deep: true,
                handler(val){
                    val && this.setAnswer();
                }
            },
            questionForm:{
                immediate:true,
                deep: true,
                handler(val){
                    this.$emit('change',val);
                }
            }
		},
		methods: {
            validateOption(rule, value, callback) {
				if ( value.answerOption === undefined || value.answerOption === ""){
                    return callback(new Error("答案不能为空"));
                }
				callback();
			},
			/**
			 * 添加选项
			 */
			add() {
                let length = this.questionForm.optionList.length;
                if(length>=26) {
                    this.$message.warning("最多可添加26个答案");
                    return;
                }
                let len = length + 65;
				this.questionForm.optionList.push({
                    optionSeq:String.fromCharCode(len),
					answerOption: "",
					isAnswer: "Y",
                    answerSeq:length+1,
                    key: Date.now()
				});
			},
			/**
			 * 删除选项
			 */
			del(index) {
				this.questionForm.optionList.splice(index, 1);
                this.questionForm.optionList.forEach((item,index)=>{
                    let len = index + 65;
                    item.optionSeq = String.fromCharCode(len);
                    item.answerSeq = index+1;
                });
			},
            setAnswer(){
                const answerOptionList = this.questionForm.optionList.filter( option=>option.isAnswer==='Y');
                const answerList =  answerOptionList.map(option=>option.answerOption);
                this.questionForm.answer =  answerList.join('※');
            },
			// 编辑
			handleEdit(value, key, index) {
				this.$emit("edit", value, key, index);
			},
            //获取题干中的（）数量
			getBracketsNum(str) {
				let BracketsNum = 0;
				str.replace(/（\s*\)|\(\s*）|\(\s*\)|（\s*）/g, () => {
					// 索引
					BracketsNum++;
				});
				return BracketsNum;
			},
            // 校验答案选择
            api_checkAnswer(){
                const { questionTitle, optionList } = this.questionForm;
				if (!this.getBracketsNum(questionTitle)) {
					this.$message.warning("题干必须包含（）");
					return false;
				}
				if (!optionList || this.getBracketsNum(questionTitle) !== optionList.length) {
					this.$message.warning("填空题的填空数量和答案数量必须一致");
					return false;
				}
				if (optionList && optionList.some(option=>option.answerOption.indexOf("※")!==-1)) {
					this.$message.warning("答案内容不能包含※");
					return false;
				}
                return  true;
            },
		}
	};
</script>
<style scoped lang="less">
	.options {
		display: flex;
		flex-direction: row;
	}
	.add-btn {
		margin: 0 10px;
	}
	.m-t15 {
		margin-top: 15px;
	}
	.tips {
		color: #666;
		font-size: 12px;
		line-height: 20px;
		display: block;
	}
	.icons {
		cursor: pointer;
		font-size: 20px;
		margin-top: 7px;
	}
	.options-item {
		margin-bottom: 15px;
		display: flex;
	}
</style>
